import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { TokenService } from '../token';

@Injectable()
export class HttpTokenInterceptors implements HttpInterceptor {

  constructor(
    private tokenService: TokenService
  ) { }

  intercept(req: HttpRequest<any>, next: HttpHandler):
    Observable<HttpEvent<any>> {
    const token  = this.tokenService.getToken();
    if (token && token.token) {
      const newreq = req.clone().headers.set('X-Requested-With', 'XMLHttpRequest').set('Authorization', 'Bearer ' + token.token);
      const authReq = req.clone({
        headers: req.headers.append('Authorization',  'Bearer ' + token.token).append('X-Requested-With', 'XMLHttpRequest')
      });
      return next.handle(authReq);
    } else {
      return next.handle(req);
    }
  }
}
